<?php


namespace App\Services;


use App\Models\Message;
use Illuminate\Support\Carbon;

class MessageService extends ApprovalService
{
    /**
     * 新增消息记录
     * $type : 1-用户审批;2-案卷审批;3-借阅审批;4-分类审批;5-导入用户出错;6-导入案卷出错;7-导入卷内出错;8-导入PDF出错;9-导出案卷为空
     */
    public static function addNewLog($type, $content, $objectId, $userId)
    {
        $arr = [
            1 => '用户审批',
            2 => '案卷审批',
            3 => '借阅审批',
            4 => '分类审批',
            5 => '导入用户出错',
            6 => '导入案卷出错',
            7 => '导入卷内出错',
            8 => '导入PDF出错',
            9 => '导出案卷为空'
        ];

        $message = new Message();

        $message->type       = $type;
        $message->content    = "【{$arr[$type]}】" . $content;
        $message->object_id  = $objectId;
        $message->company_id = company_id();
        $message->creator_id = user_id();
        $message->user_id    = $userId ?: user_id();
        $message->is_read    = 0;
        $message->save();
    }

    /**
     * 当前用户看到的消息
     */
    public function getMessages()
    {
        $list = Message::query()
            ->companyId()
            ->userId()
            ->createdAt()
            ->select('id', 'type', 'content', 'object_id', 'is_read', 'created_at')
            ->orderBy('is_read')
            ->orderByDesc('created_at')
            ->get();
        if ($list->isEmpty()) {
            return [
                'list' => [],
                'count'=> 0
            ];
        }
        $list = $list->toArray();
        foreach ($list as &$val) {
            $val['created_at'] = Carbon::parse($val['created_at'])->format('Y-m-d H:i');
            $val['for_huaman'] = Carbon::parse($val['created_at'])->diffForHumans();
        }
        return [
            'list'  => $list,
            'count' => count($list)
        ];
    }

    /**
     * 标记为已读
     */
    public function setHadRead()
    {
        CommonService::addActionLog('消息标记为已读');

        return Message::query()
            ->companyId()
            ->userId()
            ->createdAt()
            ->where('is_read', 0)
            ->update(['is_read' => 1]);
    }

    /**
     * 未读数量
     */
    public function getNoReadCount()
    {
        return Message::query()
            ->companyId()
            ->userId()
            ->where('is_read', 0)
            ->createdAt()
            ->count();
    }



}
